//
//  UserDataViewController.m
//  PrintPort
//
//  Created by 华谕 on 2017/11/14.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "UserDataViewController.h"
#import "ChangePhoneViewController.h"
#import "NickNameViewController.h"
#import "CloseAreaViewController.h"
#import "HYManageAddressViewController.h"
#import "QrCodeViewController.h"

#import "UserModel.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

static NSString *cellPath = @"UserDataCell";
@interface UserDataViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UIGestureRecognizerDelegate>
{
    UIView *ShareView;
    UIView *whiteView;
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSArray *titAry;
@property (nonatomic, strong)NSArray *rightAry;
@property (nonatomic, strong)NSArray *rightNextAry;
@property (nonatomic, strong)UserModel *model;
@property (nonatomic, strong)UIImage *faceImg;
@property (nonatomic, strong)NSString *qrCode;

@end

@implementation UserDataViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self requestGetUserInfo];
    [self requestUserRegQrCode];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _faceImg = nil;
    _qrCode = @"";
    _titAry = @[@[@"头像",@"昵称",@"ID",@"性别"],@[@"手机",@"地区",@"我的邀请码",@"二维码"],@[@"地址管理"]];
    _rightAry = @[@[@"",@"",@"",@""],@[@"",@"",@"",@""],@[@""]];
    _rightNextAry = @[@[@"0",@"1",@"0",@"1"],@[@"0",@"1",@"1",@"1"],@[@"1"]];
    [self creatUI];
}

- (void)creatUI
{
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"个人信息";
    CGFloat heightX = 0;
    if (SCREEN_HEIGHT == 812)
    {
        heightX = 34;
    }
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-heightX) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.backgroundColor = BacksColor;
    [self.view addSubview:_tableview];
    ShareView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    ShareView.backgroundColor = RGBA(0, 0, 0, 0.6);
    [sharedDelegate.window addSubview:ShareView];
    UITapGestureRecognizer *tap11 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ggViewPressed)];
    tap11.delegate = self;
    [ShareView addGestureRecognizer:tap11];
    whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-140*displaywidth-SCREER_HeiX, SCREEN_WIDTH, 140*displaywidth + SCREER_HeiX)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [ShareView addSubview:whiteView];
    NSArray *imgArray = @[@"wxfx",@"wxpyq"];
    for (int i = 0; i < imgArray.count; i++)
    {
        UIButton *shareBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2-75*displaywidth+90*displaywidth*i, 25*displaywidth, 60*displaywidth, 60*displaywidth) ImageName:imgArray[i] Target:self Action:@selector(shareAction:) Title:nil Font:12.0];
        shareBtn.tag = 60+i;
        [whiteView addSubview:shareBtn];
    }
    UILabel *tostLab = [ZCControl createLabelWithFrame:CGRectMake(0, 105*displaywidth, SCREEN_WIDTH, 25*displaywidth) Font:12.0 Text:@"分享到第三方平台" Color:RGB(158, 158, 158)];
    tostLab.textAlignment = NSTextAlignmentCenter;
    [whiteView addSubview:tostLab];
    ShareView.hidden = YES;
}

- (void)ggViewPressed
{
    ShareView.hidden = YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isDescendantOfView:whiteView]) {
        return NO;
    }
    return YES;
}

- (void)shareAction:(UIButton *)btn
{
    ShareView.hidden = YES;
    if (btn.tag == 60)
    {
        ShareManager *message = [ShareManager shareToManager];
        [message shareToType:WXSceneSession Title:@"「印港在线」" Description:@"引领行业升级\n共创美好人生" ImageUrl:@"tubiao60" WebpageUrl:[NSString stringWithFormat:@"http://app.prpor.com/#/?code=%@",_model.selfCode]];
    }
    else
    {
        ShareManager *message = [ShareManager shareToManager];
        [message shareToType:WXSceneTimeline Title:@"「印港在线」" Description:@"引领行业升级\n共创美好人生" ImageUrl:@"tubiao60" WebpageUrl:[NSString stringWithFormat:@"http://app.prpor.com/#/?code=%@",_model.selfCode]];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *titleAry = _titAry[section];
    return titleAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 44*displaywidth, SCREEN_WIDTH-15*displaywidth, 1*displaywidth)];
    lineview.backgroundColor = LinesColor;
    [cell.contentView addSubview:lineview];
    if (_model)
    {
        NSArray *titleAry = _titAry[indexPath.section];
        NSArray *rightArray = _rightAry[indexPath.section];
        NSArray *nextArray = _rightNextAry[indexPath.section];
        NSInteger isnext = [nextArray[indexPath.row] integerValue];
        cell.textLabel.text = titleAry[indexPath.row];
        cell.textLabel.font = NormalFontWithSize(14.0+fontScale);
        cell.textLabel.textColor = RGB(77, 77, 77);
        if (isnext == 1)
        {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        if (indexPath.row == titleAry.count-1)
        {
            lineview.hidden = YES;
        }
        if (indexPath.section == 0 && indexPath.row == 0)
        {
            lineview.frame = CGRectMake(15*displaywidth, 89*displaywidth, SCREEN_WIDTH-15*displaywidth, 1*displaywidth);
            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH- 110*displaywidth, 7.5*displaywidth, 75*displaywidth, 75*displaywidth) ImageName:@"face"];
            [imgView sd_setImageWithURL:[NSURL URLWithString:_model.imgUrl] placeholderImage:[UIImage imageNamed:@"face"]];
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            imgView.layer.cornerRadius = 37.5*displaywidth;
            imgView.layer.masksToBounds = YES;
            _faceImg = imgView.image;
            [cell.contentView addSubview:imgView];
        }
        else
        {
            UILabel *rightlab = [ZCControl createLabelWithFrame:CGRectMake(100*displaywidth, 5*displaywidth, SCREEN_WIDTH-135*displaywidth, 35*displaywidth) Font:14.0 Text:rightArray[indexPath.row] Color:RGB(177, 177, 177)];
            rightlab.textAlignment = NSTextAlignmentRight;
            [cell.contentView addSubview:rightlab];
        }
   
        
        
    }
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WEAKSELF;
    if (indexPath.section == 0 && indexPath.row == 0)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //拍照
        [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HYLog(@"拍照");
            [self takePhoto];
            
        }]];
        
        //从相册中选取
        [alertVC addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            HYLog(@"从相册中选取");
            [self choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
            
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            HYLog(@"取消");
            [self dismissViewControllerAnimated:NO completion:nil];
        }]];
        
        [self presentViewController:alertVC animated:YES completion:nil];
    }
     else if (indexPath.section == 0 && indexPath.row == 1)
     {
         NickNameViewController *vc = [[NickNameViewController alloc] init];
         vc.nickName = _model.nickname;
         [self.navigationController pushViewController:vc animated:YES];
     }
    else if (indexPath.section == 0 && indexPath.row == 3)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择性别" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //拍照
        [alertVC addAction:[UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSDictionary *dic= @{@"sex":@"1"};
            [weakSelf requestUpdateInfo:dic];
        }]];
        
        //从相册中选取
        [alertVC addAction:[UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSDictionary *dic= @{@"sex":@"2"};
            [weakSelf requestUpdateInfo:dic];
            
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"保密" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSDictionary *dic= @{@"sex":@"0"};
            [weakSelf requestUpdateInfo:dic];
            
        }]];
        
        [self presentViewController:alertVC animated:YES completion:nil];
    }
//    else if (indexPath.section == 1 && indexPath.row == 0)
//    {
//        ChangePhoneViewController *vc = [[ChangePhoneViewController alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
//    }
    else if (indexPath.section == 1 && indexPath.row == 1)
    {
        CloseAreaViewController *vc= [[CloseAreaViewController alloc] init];
        WEAKSELF;
        vc.chooseblock = ^(AddressModel *priveModel, AddressModel *cityModel, AddressModel *areaModel)
        {
            NSDictionary *dic = @{@"cityId": cityModel.ID,
                                  @"cityText": cityModel.name,
                                  @"provinceId": priveModel.ID,
                                  @"provinceText": priveModel.name,
                                  @"districtId":areaModel.ID,
                                  @"districtText":areaModel.name
                                  };
            [weakSelf requestUpdateInfo:dic];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.section == 1 && indexPath.row == 2)
    {
        if ([_model.selfCode isEqualToString:@""])
        {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"会员累计充值超过10元才被激活，生成推荐码" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
               
            }];
            [alertVC addAction:okAction];
            [self presentViewController:alertVC animated:YES completion:nil];
        }
        else
        {
            if ([WXApi isWXAppInstalled])
            {
                ShareView.hidden = NO;
            }
        }
    }
    else if (indexPath.section == 1 && indexPath.row == 3)
    {
        if ([_model.selfCode isEqualToString:@""])
        {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"会员累计充值超过10元才被激活，生成推荐码" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertVC addAction:okAction];
            [self presentViewController:alertVC animated:YES completion:nil];
        }
        else
        {
//            if (_faceImg)
//            {
//                QrCodeViewController *vc = [[QrCodeViewController alloc] init];
//                vc.urlStr = [NSString stringWithFormat:@"http://app.prpor.com/#/?code=%@",_model.selfCode];
//                vc.image = _faceImg;
//                [self.navigationController pushViewController:vc animated:YES];
//            }
//            else
//            {
                QrCodeViewController *vc = [[QrCodeViewController alloc] init];
                if (_qrCode.length > 0)
                {
                    vc.urlStr = _qrCode;

                }
//                vc.urlStr = [NSString stringWithFormat:@"http://app.prpor.com/#/?code=%@",_model.selfCode];
//                vc.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_model.imgUrl]]];
                [self.navigationController pushViewController:vc animated:YES];
                
//            }
            

        }
    }
    else if (indexPath.section == 2)
    {
        HYManageAddressViewController *vc = [[HYManageAddressViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)takePhoto
{
    //    判断是否打开相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您尚未开启相机权限，请去系统设置界面打开相机权限！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
        
        
    }
    else
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //            设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            
        }
        
    }
}

-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImageOrientation imageOrientation = image.imageOrientation;
        if(imageOrientation!=UIImageOrientationUp)
        {
            UIGraphicsBeginImageContext(image.size);
            [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        
    }
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HttpTool uploadImageWithPath:SERVER_fileUpload params:nil thumbName:@"file" image:image success:^(id json)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([json server_Getcodecheck])
         {
             NSArray *urlAry = json[@"data"];
             if (urlAry.count > 0)
             {
                 NSString *imgurl = urlAry[0];
                 if (imgurl.length > 0)
                 {
                     NSDictionary *dic= @{@"imgUrl":imgurl};
                     [weakSelf requestUpdateInfo:dic];
                 }
                 
             }
         }
         
     } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];

     } progress:^(CGFloat progress) {
         
     }];

    
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section != 0)
    {
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20*displayheight)];
        myView.backgroundColor = BacksColor;
        return myView;
    }
    else
    {
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
        myView.backgroundColor = [UIColor clearColor];
        return myView;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0)
    {
        return 90*displaywidth;
    }
    return 45*displaywidth;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0.01;
    }
    return 20*displaywidth;
}

- (void)requestGetUserInfo
{
    WEAKSELF;
    [HYBaseHandler requestGetUserInfoParmers:nil Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             _model = [UserModel mj_objectWithKeyValues:obj[@"data"]];
             NSString *sex = @"保密";
             if ([_model.sex integerValue] == 1)
             {
                 sex = @"男";
             }
             else if ([_model.sex integerValue] == 2)
             {
                 sex = @"女";
             }
             _rightAry = @[@[@"",_model.nickname,_model.ID,sex],@[_model.phone,[NSString stringWithFormat:@"%@-%@-%@",_model.provinceText,_model.cityText,_model.districtText],_model.selfCode,@""],@[@""]];
             dispatch_async(dispatch_get_main_queue(), ^{
                 [weakSelf.tableview reloadData];
             });
         }
         else
         {
             
         }
     } failed:^(NSError *error) {
         
     }];
}


- (void)requestUpdateInfo:(NSDictionary *)dic
{
    WEAKSELF;
    [HYBaseHandler requestUpdateInfoParmers:dic Success:^(id obj)
    {
        if ([obj server_Getcodecheck])
        {
            _model = [UserModel mj_objectWithKeyValues:obj[@"data"]];
            NSString *sex = @"保密";
            if ([_model.sex integerValue] == 1)
            {
                sex = @"男";
            }
            else if ([_model.sex integerValue] == 2)
            {
                sex = @"女";
            }
            _rightAry = @[@[@"",_model.nickname,_model.ID,sex],@[_model.phone,[NSString stringWithFormat:@"%@-%@-%@",_model.provinceText,_model.cityText,_model.districtText],_model.selfCode,@""],@[@""]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)requestUserRegQrCode
{
    WEAKSELF;
    [HYBaseHandler requestUserRegQrCodeParmers:nil Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             weakSelf.qrCode = obj[@"data"];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         
     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
